<template>
  <div class="file-rename-container">
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="400px"
      center
      :close-on-click-modal="false"
      destroy-on-close
    >
      <div class="rename-form">
        <el-form :model="formData" label-position="top" label-width="80px">
          <el-form-item label="当前路径">
            <el-input
              v-model="formData.path"
              placeholder="路径"
              disabled
              size="large"
            />
          </el-form-item>
          
          <el-form-item label="新名称" prop="newName">
            <div class="filename-input-wrapper">
              <el-input
                v-model="formData.newName"
                placeholder="请输入新名称"
                size="large"
                ref="nameInput"
                @keyup.enter="handleConfirm"
              />
              <span class="file-extension" v-if="fileExtension">.{{ fileExtension }}</span>
            </div>
            <div class="error-message" v-if="errorMessage">{{ errorMessage }}</div>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="confirmLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { getFileExtension } from '../utils/fileUtils.js'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  fileInfo: {
    type: Object,
    default: () => ({})
  }
})

// Emits
const emit = defineEmits(['update:visible', 'rename-success', 'rename-fail'])

// 响应式数据
const dialogVisible = ref(false)
const confirmLoading = ref(false)
const nameInput = ref(null)
const errorMessage = ref('')
const formData = ref({
  path: '',
  newName: ''
})

// 计算属性
const dialogTitle = computed(() => {
  return props.fileInfo.filetype === '0' ? '重命名文件夹' : '重命名文件'
})

const fileExtension = computed(() => {
  // 文件夹没有扩展名
  if (props.fileInfo.filetype === '0') return ''
  
  // 获取文件扩展名
  const extension = getFileExtension(props.fileInfo.name)
  return extension
})

const baseFilename = computed(() => {
  if (props.fileInfo.filetype === '0') {
    return props.fileInfo.name
  }
  
  const name = props.fileInfo.name
  const extension = fileExtension.value
  
  if (!extension) return name
  
  // 去掉扩展名后的文件名
  return name.substring(0, name.lastIndexOf('.'))
})

// 监听visible变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    dialogVisible.value = true
    initForm()
    nextTick(() => {
      if (nameInput.value) {
        nameInput.value.focus()
        // 选中输入框内容
        nameInput.value.select()
      }
    })
  } else {
    dialogVisible.value = false
  }
})

// 监听dialogVisible变化
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
  if (!newVal) {
    resetForm()
  }
})

// 初始化表单
const initForm = () => {
  formData.value.path = props.fileInfo.path || ''
  formData.value.newName = baseFilename.value
  errorMessage.value = ''
}

// 重置表单
const resetForm = () => {
  formData.value = {
    path: '',
    newName: ''
  }
  errorMessage.value = ''
  confirmLoading.value = false
}

// 验证表单
const validateForm = () => {
  if (!formData.value.newName.trim()) {
    errorMessage.value = '请输入新名称'
    return false
  }
  
  // 检查文件名是否包含特殊字符
  const invalidChars = /[\\/:*?"<>|]/g
  if (invalidChars.test(formData.value.newName)) {
    errorMessage.value = '文件名不能包含以下字符: \\ / : * ? " < > |'
    return false
  }
  
  // 检查文件名长度
  if (formData.value.newName.length > 255) {
    errorMessage.value = '文件名长度不能超过255个字符'
    return false
  }
  
  // 检查是否与原文件名相同
  const fullNewName = props.fileInfo.filetype === '0' 
    ? formData.value.newName 
    : `${formData.value.newName}.${fileExtension.value}`
  
  if (fullNewName === props.fileInfo.name) {
    errorMessage.value = '新名称与原名称相同'
    return false
  }
  
  errorMessage.value = ''
  return true
}

// 处理确认
const handleConfirm = async () => {
  if (!validateForm()) {
    nextTick(() => {
      if (nameInput.value) {
        nameInput.value.focus()
      }
    })
    return
  }
  
  confirmLoading.value = true
  
  try {
    // 构建完整的新文件名
    const fullNewName = props.fileInfo.filetype === '0' 
      ? formData.value.newName 
      : `${formData.value.newName}.${fileExtension.value}`
    
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 构建返回的数据
    const result = {
      id: props.fileInfo.id,
      fid: props.fileInfo.fid,
      oldName: props.fileInfo.name,
      newName: fullNewName,
      filetype: props.fileInfo.filetype
    }
    
    ElMessage.success('重命名成功')
    emit('rename-success', result)
    dialogVisible.value = false
  } catch (error) {
    console.error('重命名失败:', error)
    ElMessage.error('重命名失败，请重试')
    emit('rename-fail', error)
  } finally {
    confirmLoading.value = false
  }
}

// 处理取消
const handleCancel = () => {
  dialogVisible.value = false
}
</script>

<style scoped>
.file-rename-container {
  font-size: 14px;
}

.rename-form {
  padding: 10px 0;
}

.filename-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.file-extension {
  position: absolute;
  right: 12px;
  color: #909399;
  font-size: 14px;
  pointer-events: none;
}

:deep(.el-input__wrapper) {
  padding-right: 50px;
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  margin-bottom: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  :deep(.el-dialog) {
    width: 90% !important;
    max-width: 400px;
  }
}
</style>